<?php

namespace App\Http\Controllers\Admin\V1;

use App\Exports\UserExcelModel;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\UserRequest;
use App\Imports\UserImport;
use App\Models\Role;
use App\Models\Section;
use App\Models\User;
use App\Transformers\Admin\UserTransformer;
use Dingo\Api\Http\Response;
use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class UserController extends Controller
{
    /**
     * 用户列表
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        $users = User::pimp()->paginate($this->pageLimit());

        return $this->response->paginator($users, new UserTransformer());
    }

    /**
     * 获取用户详情
     *
     * @param User $user
     * @return Response
     */
    public function show(User $user): Response
    {
        return $this->response->item($user, new UserTransformer());
    }

    /**
     * 用户添加
     *
     * @param UserRequest $request
     * @return void
     */
    public function store(UserRequest $request)
    {
        try {
            DB::beginTransaction();

            $user = User::create([
                'username' => $request->input('username'),
                'name' => $request->input('name'),
                'email' => $request->input('email'),
                'phone' => $request->input('phone'),
                'id_card' => $request->input('id_card'),
                'password' => $request->input('password')
            ]);

            if (!empty($request->input('roles'))) {
                // 分配角色
                $user->syncRoles($request->input('roles'));
            }

            if (!empty($request->input('section'))) {
                // 获取部门数据
                $sections = Section::query()
                    ->select('id', 'pid')
                    ->with('parent', function ($query) {
                        $query->select('id', 'pid')->with('parent:id,pid');
                    })
                    ->whereIn('id', $request->input('section'))
                    ->get()
                    ->toArray();

                $pivotId = $this->path($sections);

                foreach ($request->input('section') as $key => $value) {
                    $path = ',' . (implode(',', array_reverse($pivotId))) . ',' . $value . ',';

                    $user->section()->attach($value, ['section_id' => $value, 'path' => $path]);
                }
            }

            DB::commit();

            return $this->response->created();

        } catch (Exception $e) {
            report($e);

            DB::rollBack();
            return $this->response->error('未知错误', '500');
        }
    }

    /**
     * 组装path
     *
     * @param $data
     * @return array|false
     */
    public function path($data)
    {
        static $path = array();

        if (empty($data)) {
            return false;
        }

        foreach ($data as $key => $value) {
            array_push($path, $value['pid']);

            if (isset($value['parent'])) {
                $this->path($value['parent']);
            }
        }
        return $path;
    }

    /**
     * 修改
     *
     * @param UserRequest $request
     * @param User $user
     * @return Response|void
     * @throws AuthorizationException
     */
    public function update(UserRequest $request, User $user)
    {
        // 判断权限
        if ($this->adminUser()->id() !== $user->id) {
            if ($user->hasRole(Role::SUPER_ADMIN)) {
                throw new authorizationexception;
            }
        }

        try {
            DB::beginTransaction();

            $user->update($request->all());

            if (!empty($request->input('roles'))) {
                // 分配角色
                $user->syncRoles($request->input('roles'));
            }

           if (!empty($request->input('section'))) {
               // 获取部门数据
               $sections = Section::query()
                   ->whereIn('id', $request->input('section'))
                   ->select('id', 'pid')
                   ->with('parent', function ($query) {
                       $query->select('id', 'pid')->with('parent:id,pid');
                   })
                   ->get()
                   ->toArray();

               $userHasSection = [];

               foreach ($user->section()->get() as $model) {
                   array_push($userHasSection, $model->pivot->section_id);
               }

               // 数组反转
               $pivotId = array_reverse($this->path($sections));

               $expires = [];

               foreach ($request->input('section') as $key => $value) {
                   array_push($pivotId, $value);
                   // 数组去重
                   $arr = array_unique($pivotId);
                   $path = ',' . (implode(',', $arr)) . ',';

                   $expires[$value] = ['path' => $path];
               }

               $user->section()->sync($expires);
           }

            DB::commit();

            return $this->response->noContent();

        } catch (Exception $e) {
            report($e);

            DB::rollBack();
            return $this->response->error('未知错误', '500');
        }
    }

    /**
     * 禁用启用
     *
     * @param User $user
     * @return Response
     * @throws AuthorizationException
     */
    public function destroy(User $user): Response
    {
        if ($user->hasRole(Role::SUPER_ADMIN)) {
            throw new authorizationexception;
        }

        $user->status = !$user->status;
        $user->save();

        return $this->response->noContent();
    }

    /**
     * 重置密码
     *
     * @param Request $request
     * @param User $user
     * @return Response
     * @throws AuthorizationException
     */
    public function password(Request $request, User $user): Response
    {
        if ($user->hasRole(Role::SUPER_ADMIN)) {
            throw new authorizationexception;
        }

        $validator = $request->validate([
            'password' => 'required|min:6|max:32'
        ]);

        $user->password = $validator['password'];
        $user->save();

        return $this->response->noContent();
    }

    /**
     * 下载模板
     */
    public function export(): \Symfony\Component\HttpFoundation\BinaryFileResponse
    {
        return Excel::download(new UserExcelModel(),'user.model.xlsx', \Maatwebsite\Excel\Excel::XLSX);
    }

    /**
     * 批量导入
     *
     * @param Request $request
     * @return Response|void
     */
    public function import(Request $request)
    {
        $request->validate([
            'file' => ['bail', 'required', 'file'],
        ]);

        //获取文件类型后缀
        $extension = $request->file('file')->getClientOriginalExtension();

        if ($extension != 'xlsx') {
            return $this->response->error('上传的文件不是excel文件', 422);
        }

        Excel::import(new UserImport(), $request->file('file'));

        return $this->response->created();
    }
}
